
import { uniqBy, cloneDeep } from 'lodash'
import { storage } from "@/utils/storage";
/* 数组转树 */
/* 数组转树 */
export const arrayToTree = (arr, id = 'id', parentId = 'parent_id', children = 'children', hasChildren = 'hasChildren') => {
  const tree = []
  const map = {}

  // 创建节点映射，以便能够快速查找父节点
  arr.forEach(item => {
    map[item[id]] = { ...item, [children]: [] }
  })

  // 构建树结构
  arr.forEach(item => {
    if (item[parentId] !== 0) {
      if(map[item[parentId]]){
        map[item[parentId]][children].push(map[item[id]])
        // map[item[parentId]][hasChildren] = true
      }else {
        tree.push(map[item[id]])
      }
      
    } else {
      tree.push(map[item[id]])
    }
  })

  return tree
}


export const treeToArray = (tree, children = 'children') => {
  const result = [];
  const stack = [...tree];
 
  while (stack.length) {
    const item = stack.pop();
    result.push(item);
    if (item[children]) {
      stack.push(...item[children]);
    }
  }
  return result;
}


/*
  *@method 对象数组根据key值去重
  *@param  string  name  key,指定去重id
  *@param  data  去重数组  
  *@return
  */
export const unique = (data, key = 'id')=> {
  return uniqBy(data, key);
}

/*
*@method 对象数组根据key值去重
*@param  string  name  key,指定去重id
*@param  data  去重数组  
*@return
*/
export const exportExcel = (data, filename)=> {
  let blob = new Blob([data], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
  });
  let objectUrl = URL.createObjectURL(blob);
  let link = document.createElement("a");
  link.href = objectUrl;
  link.setAttribute("download", filename);
  document.body.appendChild(link);
  link.click();
}

/*
*@method 文件大小格式化显示工具
*@param  number  bytes  文件大小
*@param  decimalPoint  小数点位数
*@return
*/
export const formatFileSize = (bytes,  decimalPoint)=> {
  if(bytes == 0) return '0 Bytes';
  let binary = 1024,
      decimal = decimalPoint || 2,
      sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
      index = Math.floor(Math.log(bytes)/Math.log(binary));
  return parseFloat((bytes/Math.pow(binary, index)).toFixed(decimal)) + ' ' + sizes[index];
}


/*
*@method  获取某个时间戳，24点时间戳
*@param  timestamp  
*@return
*/
export const getMidnightTimestamp= (timestamp)=> {
  if(!timestamp) return new Date().getTime();
  // 将时间戳转换为日期对象
  const date = new Date(timestamp);
  // 将时间设置为当天的 24:00:00
  date.setHours(24, 0, 0, 0);
  // 获取当天 24 点的时间戳
  return date.getTime();
}

/*
*@method  深拷贝
*@param  data  
*@return
*/
export const copyDeep= (data)=> {
  return cloneDeep(data)
}

/*
*@method  获取函数体
*@param  data  
*@return
*/
export const extractFunctionBody= (fn)=> {
  const regex = /{([\s\S]*)}/;
  const match = fn.toString().match(regex);
  if (match) {
    let body = match[1].trim();
    if (body.startsWith('return ')) {
      body = body.substring(7);
    }
    return body.trim();
  }
  return '';
}

/*
*@method  同key对象快速赋值，把obj2值赋给obj1，但是只保留obj1的属于
*@param  obj1  
*@param  obj2
*@return
*/
export const objectAssignment= (obj1, obj2)=> {
  Object.keys(obj1).forEach(key => {
    if(obj2.hasOwnProperty(key)){
      obj1[key] = obj2[key];
    }
  });
}


export function transformArray(data, key, value) {
  return data.map(item => ({
      label: item[key] || '', // 如果指定的key不存在，则返回空字符串
      value: item[value] || '' // 如果指定的value不存在，则返回空字符串
  }));
}

export function transformObject(data, key, value) {
	let arr = {};
	for(let i in data) {
		arr[data[i][key]] = data[i][value];
	}
	return arr;
}
export function getLable(data, value) {
  console.log(data, value,'valuevaluevaluevaluevaluevaluevalue' )
	let obj = data.find((item)=>{
		return item.value == value
	})
	if(obj){
		return obj.label
	}else {
		return '-'
	}
}


export function formatNumber(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
